# -*- coding: utf-8 -*-
import sys,os
from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice
from com.android.monkeyrunner.easy import By

CMD_MAP = {
    'TOUCH': lambda dev, arg: dev.touch(**arg),
    'DRAG': lambda dev, arg: dev.drag(**arg),
    'PRESS': lambda dev, arg: dev.press(**arg),
    'TYPE': lambda dev, arg: dev.type(**arg),
    'WAIT': lambda dev, arg: MonkeyRunner.sleep(**arg)
    }

def process_file(fp, device):
    for line in fp:
        (cmd, rest) = line.split('|')
        try:
            # Parse the pydict
            rest = eval(rest)
        except:
            print 'unable to parse options'
            continue

        if cmd not in CMD_MAP:
            print 'unknown command: ' + cmd
            continue

        CMD_MAP[cmd](device, rest)

def main():
    file = sys.argv[1]
    fp = open(file, 'r')

    device = MonkeyRunner.waitForConnection(3)

    fd = os.popen('adb devices')
    output = fd.read()
    fd.close()
    device_num = len(output.splitlines()) - 2

    if device_num > 0:
        print >> sys.stderr, 'success'
    else:
        print >> sys.stderr,"fail"
        sys.exit(1)

    device.removePackage('com.ymatou.shop')
    device.installPackage('D:/ymatou3.5.0-buyer-official-20170427.apk')

    MonkeyRunner.sleep(3)

    #device.startActivity(component='com.ymatou.shop/com.ymatou.shop.ui.activity.SplashActivity')
    device.startActivity(component = 'com.ymatou.shop/com.ymatou.shop.reconstract.MainActivity')
    easy_device = EasyMonkeyDevice(device)
    #device.press('KEYCODE_BACK', MonkeyDevice.DOWN_AND_UP)
    MonkeyRunner.sleep(10)
    easy_device.touch(By.id('id/tv_home_coupon_dialog_go'), MonkeyDevice.DOWN_AND_UP)
    #process_file(fp, device)
    fp.close();

if __name__ == '__main__':
    main()


